from random import choice

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
from django.core.mail import send_mail
from django.db.models import Q
from django.http import Http404
from django.shortcuts import render
from rest_framework import mixins, generics, views, viewsets, status
from rest_framework.authentication import TokenAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
import json

from .models import EmailVerifyRecord,User,UserErrorBook
from words_site import settings
from .serializers import EmailSerializer,CodeSerlializer,UserInfoSerializer,ErrorBookSerializer,\
    DelErrorBookSerializer,PasswordSerializer
# Create your views here.

global null
null=""
class SendEmailcodeView(mixins.CreateModelMixin,viewsets.GenericViewSet):

    serializer_class = EmailSerializer
    def code(self):
        seeds = "1234567890"
        random_str = []
        for i in range(4):
            random_str.append(choice(seeds))
        return "".join(random_str)
    def create(self, request, *args, **kwargs):
        serializer=self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        email=serializer.validated_data["email"]
        email_type=serializer.validated_data["email_type"]

        code=self.code()
        flag = send_mail('验证码','[验证码]'+code + '验证码20分钟内有效,请及时输入！',settings.EMAIL_HOST_USER,
                         [email],
                         fail_silently=False,)

        if flag == 1:
            code_record = EmailVerifyRecord.objects.create(code=code, email=email,email_type=email_type)
            code_record.save()
            return Response({"email": email}, status=status.HTTP_201_CREATED)



class RegisterViews(views.APIView):

    def post(self, request, format=None):
        serializer = CodeSerlializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        data=eval(json.dumps(serializer.data))

        result=User.objects.create(username=data["username"],password=make_password(data["password"]),
                                   email=data["email"])
        del data["code"]
        del data["password"]
        if result:
            return Response(data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class GetUserViewSet(mixins.ListModelMixin,generics.GenericAPIView):

    queryset = User.objects.all()
    serializer_class = UserInfoSerializer
    lookup_field="username"
    permission_classes = (IsAuthenticated,)
    authentication_classes = (TokenAuthentication, SessionAuthentication)

    def get_queryset(self):
        user = self.kwargs["username"]
        return User.objects.filter(username=user)

    def get(self, request,*args,**kwargs):
        return self.list(request,*args,**kwargs)


class UpdateUserInfoView(mixins.UpdateModelMixin,generics.GenericAPIView):

    queryset = User.objects.all()
    serializer_class = UserInfoSerializer

    lookup_field="username"

    def get_queryset(self):
        user = self.kwargs["username"]
        return User.objects.filter(username=user)

    def put(self, request, *args, **kwargs):
        return self.update( request, *args, **kwargs)

    def patch(self, request, *args, **kwargs):
        return self.partial_update(request,*args,**kwargs)



class CustomBackend(ModelBackend):
    # 重写authenticate方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 重点就是这一句了
        user = User.objects.filter(Q(username=username) | Q(email=username)).first()
        if user:
            if user.check_password(password):
                return user
        return None



class UserErrorBookView(generics.CreateAPIView):

    serializer_class = ErrorBookSerializer

    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)

class DeleteAllOfErrorBookView(mixins.DestroyModelMixin,generics.GenericAPIView):
    queryset = UserErrorBook.objects.all()
    serializer_class = DelErrorBookSerializer
    lookup_field = "username"

    def get_queryset(self):
        user = self.kwargs["username"]
        return UserErrorBook.objects.filter(username=user)

    def delete(self,request,*args,**kwargs):
        serializer=self.get_queryset()
        serializer.delete()
        return Response({"status":"success"},status=status.HTTP_200_OK)



class ChangePasswordView(generics.GenericAPIView):

    queryset = User.objects.all()
    serializer_class = PasswordSerializer

    def put(self,request):
        serializer=self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        return Response(status=status.HTTP_200_OK)




